﻿using System;
using System.Collections.Generic;
using System.Linq;
using BML.Infrastructure.Platform;
using Model.Platform.PhysicalData;
using Service.Infrastructure.Interface;
using Service.Infrastructure.Model;
using Service.Infrastructure.Result;

namespace Service.Infrastructure.Implement
{
    /// <summary>
    ///     平台配置-重要类，若无需要请勿修改
    /// </summary>
    public class PlatformConfigService : BaseService, ISetting, IPlatformInitialization
    {
        protected readonly SystemicSetting SystemicSettingOp = new SystemicSetting();



        /// <summary>
        ///     初始化系统信息保存到全局变量及数据库中,该方法只会在系统初始的时候加载一次
        /// </summary>
        public void Init()
        {
            var setting = new SystemicSetting();
            //初始到数据库中
            setting.SetPlatformConfig(new Dictionary<String, String>
                {
                    {FormatKey(SettingKey.SmtpUser,EnvirType.Mail), "framework-server@defshare.com"},
                    {FormatKey(SettingKey.SmtpPwd,EnvirType.Mail), "share123"},
                    {FormatKey(SettingKey.SmtpUrl,EnvirType.Mail), "smtp.exmail.qq.com"},
                    {FormatKey(SettingKey.EmailPwdRoute,EnvirType.Mail), ""},

                    {FormatKey(SettingKey.InitPassword,EnvirType.Other),"Dongyan"},
                    {FormatKey(SettingKey.AdminWebsiteTitle,EnvirType.Other),"Se7en's Admin Dashboard Template"}
                    
                });
            //初始到全局变量中                     
            MemoryCache.CacheSetting = setting.PlatformConfigByDictionary();

        }

        /// <summary>
        ///     格式化主键
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static String FormatKey(String key, Int32 type)
        {
            const String str = "{0}-{1}";
            return String.Format(str, key, type);
        }













        #region 平台配置逻辑


        /// <summary>
        ///     从数据中获取数据，仅供外部查询，不更新或查询缓存
        /// </summary>
        /// <returns></returns>
        public ServiceResult QueryConfig()
        {

            var srcList = SystemicSettingOp.PlatformConfig();
            return Result(ResultType.OperateQueryIsSuccess, new Dictionary<Int32, IList<SettingConfigModel>>
            {
                {EnvirType.Mail,QueryConfig(srcList,EnvirType.Mail)},
                {EnvirType.Other,QueryConfig(srcList,EnvirType.Other)}
            });
        }

        private List<SettingConfigModel> QueryConfig(IEnumerable<Setting> srcList, Int32 configType)
        {
            return srcList.Where(n => n.Type == configType).Select(ConverModel).OrderByDescending(m => m.Key).ToList();
        }

        /// <summary>
        ///     更新缓存，更新数据库
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public ServiceResult ChangeConfig(ref Dictionary<string, string> dict)
        {

            var newDict = ClearDict(ref dict);


            //数据库更新
            SystemicSettingOp.ChangePlatformConfig(newDict);

            //缓存更新
            foreach (var d in newDict)
            {
                if (MemoryCache.CacheSetting.ContainsKey(d.Key))
                {
                    MemoryCache.CacheSetting[d.Key] = d.Value;
                }
            }


            return Result(ResultType.OperateUpdateIsSuccess);
        }

        /// <summary>
        ///     清楚为空的字键
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        private Dictionary<string, string> ClearDict(ref Dictionary<string, string> dict)
        {
            return dict.Where(m => !ParamsIsNull(m.Value)).ToDictionary(m => m.Key, m => m.Value.Trim());
        }

        public SettingConfigModel ConverModel(Setting m)
        {
            return new SettingConfigModel
            {
                Id = m.Id,
                Key = m.KeyWord,
                Type = m.Type.ToString(),
                Value = m.Value,
            };
        }






        /// <summary>
        ///     添加一条系统配置
        /// </summary>
        /// <param name="keyWord"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ServiceResult CreateSysConfig(String keyWord, String value)
        {
            throw new NotImplementedException("PlatformConfigService-CreateSysConfig");
        }



        /// <summary>
        ///     删除系统配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ServiceResult DelSysConfig(Guid id)
        {
            throw new NotImplementedException("PlatformConfigService-DelSysConfig");
        }

        #endregion

    }
}
